"""调查 API Router."""
from typing_extensions import Annotated
from fastapi import APIRouter, BackgroundTasks, Depends, Path, Request

from api.v1.service.point import PointServiceAPI
from core.models import Member, Poll, PollEtc
from lib.mail import send_poll_etc_mail
from api.v1.dependencies.member import get_current_member_optional
from api.v1.dependencies.poll import (
    get_poll, get_poll_etc, validate_poll_etc_create, validate_poll_etc_delete,
    validate_poll_read, validate_poll_update
)
from api.v1.service.poll import PollServiceAPI
from api.v1.models.response import (
    MessageResponse, response_403, response_404, response_409, response_422,
    response_500
)
from api.v1.models.poll import (
    CreatePollEtc, LatestPollResponse, PollResponse
)

router = APIRouter()


@router.get("/polls/latest",
            summary="最新调查 1干燥回路",
            responses={**response_500})
async def read_poll_latest(
    service: Annotated[PollServiceAPI, Depends()],
) -> LatestPollResponse:
# """
# 查看最新的1项调查。
# -使用LRU（Least Recently Used）缓存进行查询。
# """
    return service.fetch_latest_poll()


@router.get("/polls/{po_id}",
            dependencies=[Depends(validate_poll_read)],
            summary="调查查询",
            responses={**response_403, **response_404})
async def read_poll(
    service: Annotated[PollServiceAPI, Depends()],
    poll: Annotated[Poll, Depends(get_poll)],
) -> PollResponse:
    """
   查询调查信息。
    """
    total_vote, items = service.calculate_poll_result(poll)
    other_polls = service.fetch_other_polls(poll.po_id)

    return {
        "poll": poll,
        "total_vote": total_vote,
        "items": items,
        "etcs": poll.etcs,
        "other_polls": other_polls
    }


@router.patch("/polls/{po_id}/{item}",
              dependencies=[Depends(validate_poll_update)],
              summary="参与调查",
              responses={**response_403, **response_404, **response_409})
async def update_poll(
    service: Annotated[PollServiceAPI, Depends()],
    point_service: Annotated[PointServiceAPI, Depends()],
    member: Annotated[Member, Depends(get_current_member_optional)],
    poll: Annotated[Poll, Depends(get_poll)],
    item: Annotated[int, Path(title="问题项目编号", description="问题项目编号", ge=1, le=9)],
) -> MessageResponse:
# """
# 对调查项目进行投票。
# -如果您没有权限或已经参与，则无法投票。
# -如果设置了积分，投票时将获得积分。
# """
    poll = service.update_poll(poll, item, member)

    # 点数支付
    if member:
        content = f'{poll.po_id}. {poll.po_subject[:20]} 参与调查'
        point_service.save_point(member.mb_id, poll.po_point, content,
                                 '@poll', poll.po_id, '投票')

    return {"message": "参与调查已完成."}


@router.post("/polls/{po_id}/etc",
             dependencies=[Depends(validate_poll_etc_create)],
             summary="其他意见的登记",
             responses={**response_403, **response_404, **response_422})
async def create_poll_etc(
    request: Request,
    background_tasks: BackgroundTasks,
    service: Annotated[PollServiceAPI, Depends()],
    member: Annotated[Member, Depends(get_current_member_optional)],
    poll: Annotated[Poll, Depends(get_poll)],
    data: CreatePollEtc,
) -> MessageResponse:
# """
# 注册调查的其他意见。
# -只有在您可以注册其他评论的问卷调查中才能注册。
# -作者可以注册为会员或非会员。
# -注册其他评语时，将向最高管理员发送邮件。（设置邮件发送时）

# ### Request Body
# -**pc_name**：作者
# -**pc_idea**：其他评论
# """
    poll_etc = service.create_poll_etc(poll, member, **data.__dict__)

    # 邮寄其他评论
    background_tasks.add_task(send_poll_etc_mail, request, poll_etc)

    return {"message": "其他评论已注册."}


@router.delete("/polls/{po_id}/etc/{pc_id}",
               dependencies=[Depends(validate_poll_etc_delete)],
               summary="删除其他评论",
               responses={**response_403, **response_404, **response_404})
async def delete_poll_etc(
    poll_service: Annotated[PollServiceAPI, Depends()],
    poll_etc: Annotated[PollEtc, Depends(get_poll_etc)],
) -> MessageResponse:
    """
    删除其他评论.
    """
    poll_service.delete_poll_etc(poll_etc)

    return {"message": "其他评论已被删除."}
